<template>
  <div class="welcome-container">
    <!-- 顶部导航栏 -->
    <el-header class="header">
      <div class="user-info">
<!--        <el-avatar :size="40" :src="userAvatar" class="avatar"></el-avatar>-->
        账号:
        <el-dropdown @command="handleCommand">
          <span class="el-dropdown-link">
            {{ users.username }}<i class="el-icon-arrow-down el-icon--right"></i>
          </span>
        </el-dropdown>
      </div>
    </el-header>

    <!-- 主要内容区域 -->
    <el-main class="main-content">
      <!-- 欢迎标语 -->
      <div class="welcome-banner">
        <h1>欢迎回来，{{ escort.name }}！</h1>
        <p>您今天的陪伴将温暖患者的心灵 ❤️</p>
      </div>

      <!-- 数据概览卡片 -->
      <el-row :gutter="20" class="data-card-group">
        <el-col :span="8">
          <el-card class="data-card">
            <div class="card-content">
              <i class="el-icon-wallet card-icon"></i>
              <div>
                <div class="card-title">护士Id</div>
                <div class="card-value">{{ escort.escortId }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="data-card">
            <div class="card-content">
              <i class="el-icon-s-order card-icon"></i>
              <div>
                <div class="card-title">性别</div>
                <div class="card-value">{{ escort.gender }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="data-card">
            <div class="card-content">
              <i class="el-icon-star-off card-icon"></i>
              <div>
                <div class="card-title">年龄</div>
                <div class="card-value">{{ escort.age }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <el-row :gutter="20" class="data-card-group">
        <el-col :span="8">
          <el-card class="data-card">
            <div class="card-content">
              <i class="el-icon-wallet card-icon"></i>
              <div>
                <div class="card-title">联系电话</div>
                <div class="card-value">{{ escort.contactNumber }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="data-card">
            <div class="card-content">
              <i class="el-icon-s-order card-icon"></i>
              <div>
                <div class="card-title">资质证书编号</div>
                <div class="card-value">{{ escort.qualificationCertificate }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="data-card">
            <div class="card-content">
              <i class="el-icon-star-off card-icon"></i>
              <div>
                <div class="card-title">入职时间</div>
                <div class="card-value">{{ formatDate_hireDate }}</div>
                <div>
                  <el-date-picker
                      v-model="escort.hireDate"
                      placeholder="选择入职日期"
                      value-format=""
                      disabled
                  >
                  </el-date-picker></div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 快速操作区 -->
      <el-row :gutter="20" class="quick-actions">
        <el-col :span="6">
          <el-button
              type="primary"
              icon="el-icon-plus"
              class="action-button"
              @click="router().push('serviceRecord1')">
            接新订单
          </el-button>
        </el-col>
        <el-col :span="6">
          <el-button
              type="success"
              icon="el-icon-tickets"
              class="action-button"
              @click="router().push('serviceRecord2')">
            我的订单
          </el-button>
        </el-col>
        <el-col :span="6">
          <el-button
              type="info"
              icon="el-icon-date"
              class="action-button"
              @click="router().push('plan')">
            日程安排
          </el-button>
        </el-col>
        <el-col :span="6">
          <el-button
              type="warning"
              icon="el-icon-setting"
              class="action-button"
              @click="showEditDialog()">
            修改护士信息
          </el-button>
        </el-col>
      </el-row>

      <!-- 公告区域 -->
<!--      <el-card class="announcement">
        <div slot="header" class="announcement-header">
          <i class="el-icon-megaphone"></i>
          <span>最新公告</span>
        </div>
        <div class="announcement-content">
          {{ latestAnnouncement }}
        </div>
      </el-card>-->
    </el-main>
  </div>

  <!-- 编辑用户信息对话框 -->
  <!--    模态框-->
  <el-dialog v-model="dialogFormVisible" title="言㐱陪诊" width="500">
    <!-- 为 el-form 添加 :rules 属性和 ref -->
    <el-form :model="form" :rules="rules" ref="formRef" label-position="right" label-width="auto">
      <!--      //***-->
      <!-- 为每个 el-form-item 添加 prop 属性 -->
      <el-form-item label="陪诊人员姓名" prop="name">
        <el-input v-model="form.name" autocomplete="off" placeholder="请输入陪诊人员姓名" />
      </el-form-item>
      <el-form-item label="陪诊人员性别" prop="gender">
        <el-input v-model="form.gender" autocomplete="off" placeholder="请输入陪诊人员性别" />
      </el-form-item>
      <el-form-item label="陪诊人员年龄" prop="age">
        <el-input v-model.number="form.age" autocomplete="off" placeholder="请输入陪诊人员年龄" />
      </el-form-item>
      <el-form-item label="陪诊人员联系电话" prop="contactNumber">
        <el-input v-model="form.contactNumber" autocomplete="off" placeholder="请输入陪诊人员联系电话" />
      </el-form-item>
      <el-form-item label="陪诊人员资质证书编号" prop="qualificationCertificate">
        <el-input v-model="form.qualificationCertificate" autocomplete="off" placeholder="请输入陪诊人员资质证书编号" />
      </el-form-item>
      <el-form-item label="陪诊人员入职日期" prop="hireDate">
        <el-date-picker
            v-model="form.hireDate"
            type="date"
            placeholder="选择入职日期"
            value-format=""
        >
        </el-date-picker>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="!isEdit" type="primary" @click="handleAdd">新增</el-button>
        <el-button v-else type="primary" @click="handleEdit">修改</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import axios from "axios";
import {ElMessage} from "element-plus";
import {mapGetters} from "vuex";
import {createRouter as $router} from "vue-router";
import router from "@/router/index.js";

export default {
  computed: {
    ...mapGetters(['getUserId'])
  },
  data() {
    return {
      formatDate_hireDate:'',
      users: {},
      escort: {
        name: "空",
        gender: "空",
        age: 99,
        contactNumber: "空",
        qualificationCertificate: "空",
        hireDate: null,
      },
      dialogFormVisible: true,
      isEdit: false,
      // 定义验证规则
      rules: {
        name: [
          { required: true, message: '请输入陪诊人员姓名', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请输入陪诊人员性别', trigger: 'blur' }
        ],
        age: [
          { required: true, message: '请输入陪诊人员年龄', trigger: 'blur' },
          { type: 'number', message: '年龄必须为数字', trigger: 'blur' }
        ],
        contactNumber: [
          { required: true, message: '请输入陪诊人员联系电话', trigger: 'blur' }
        ],
        qualificationCertificate: [
          { required: true, message: '请输入陪诊人员资质证书编号', trigger: 'blur' }
        ],
        hireDate: [
          { required: true, message: '请选择陪诊人员入职日期', trigger: 'change' }
        ]
      },
      form: {
        name: "xxx",
        gender: "x",
        age: 99,
        contactNumber: "9999",
        qualificationCertificate: "999",
        hireDate: null,
      },
      userName: "王护士",
      userAvatar: "https://example.com/avatar.jpg",
      todayOrders: 3,
      monthlyIncome: "4,800",
      rating: "4.9",
      latestAnnouncement: "系统将于今晚23:00进行维护升级，预计耗时1小时。"
    };
  },
  created() {
    this.getEscortInfo();
    this.getPatientInfo();
  },
  methods: {
    router() {
      return router
    },
    $router,
    handleCommand(command) {
      if (command === "logout") {
        this.$confirm('确定要退出登录吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 这里执行退出登录逻辑
          this.$router.push('/login');
        });
      } else if (command === "profile") {
        this.$router.push('/profile');
      }
    },
    async getPatientInfo() {
      const userId = this.getUserId;
      if (userId) {
        try {
          const res = await axios.get(`/api/wu_vue_2_test/User/getById?id=${userId}`);
          if (res.data.code === 200) {
            console.log(res.data);
            this.users  = res.data.data;
          } else {
            ElMessage.error(res.data.message);
          }
        } catch (error) {
          console.error('请求出错:', error);
          ElMessage.error('请求出错，请稍后重试');
        }
      } else {
        ElMessage.error('未获取到用户信息，请重新登录');
        this.$router.push('/login');
      }
    },
    async getEscortInfo() {
      const userId2 = this.getUserId;
      if (userId2) {
        try {
          const res = await axios.get(`/api/wu_vue_2_test/Escort/GetEscortByUserId?UserId=${userId2}`);
          if (res.data.code === 200) {
            console.log(res.data);
            this.escort  = res.data.data;
            this.form=this.escort;
          } else {
            ElMessage.error(res.data.message);
          }
        } catch (error) {
          console.error('请求出错:', error);
          ElMessage.error('请求出错，请稍后重试');
        }
      } else {
        ElMessage.error('未获取到用户信息，请重新登录');
        this.$router.push('/login');
      }
    },
    // 4.修改当前行数据
    async handleEdit() {
      // 调用表单验证方法
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            const res = await axios.post(
                "/api/wu_vue_2_test/Escort/update",
                this.form
            );
            this.dialogFormVisible = false;
            await this.getTableData();
            this.showMsg(res);
          } catch (error) {
            console.error("修改数据失败,被占用或网络不佳:", error);
            ElMessage({
              message: "修改数据失败,被占用或网络不佳，请稍后重试",
              type: "error",
              plain: true,
            });
          }
        } else {
          console.log('表单验证不通过');
          return false;
        }
      });
    },
    // 显示编辑对话框
    showEditDialog() {
      this.dialogFormVisible = true;
      this.isEdit = true;
      this.form=this.escort;
    },
    // 重置表单
    resetForm() {
      this.form = {
        name: "",
        gender: "",
        age: null,
        contactNumber: "",
        qualificationCertificate: "",
        hireDate: null,
      };
    },
    // 显示操作结果消息
    showMsg(res) {
      if (res.data.code === 200) {
        ElMessage({
          message: res.data.msg,
          type: "success",
          plain: true,
        });
      } else {
        ElMessage({
          message: res.data.msg,
          type: "error",
          plain: true,
        });
      }
    },
    formatDate(date) {
      if (typeof date === 'string') {
        // 尝试使用标准的日期格式解析
        const parsedDate = new Date(date);
        if (!isNaN(parsedDate.getTime())) {
          date = parsedDate;
        } else {
          // 如果标准格式解析失败，可以考虑手动解析
          // 这里假设后端返回的是 yyyy-MM-dd 格式
          const parts = date.split('-');
          if (parts.length === 3) {
            const year = parseInt(parts[0], 10);
            const month = parseInt(parts[1], 10) - 1; // 月份从 0 开始
            const day = parseInt(parts[2], 10);
            date = new Date(year, month, day);
          }
        }
      }
      if (date instanceof Date &&!isNaN(date.getTime())) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      }
      return '';
    }

  }
};
</script>

<style scoped>
.welcome-container {
  height: 100vh;
  background-color: #f5f7fa;
}

.header {
  background-color: #ffffff;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.welcome-banner {
  text-align: center;
  margin: 40px 0;
}
.welcome-banner h1 {
  color: #303133;
  margin-bottom: 15px;
}
.welcome-banner p {
  color: #606266;
  font-size: 16px;
}

.data-card-group {
  margin-bottom: 30px;
}

.data-card {
  margin-bottom: 20px;
}
.card-content {
  display: flex;
  align-items: center;
  padding: 20px;
}
.card-icon {
  font-size: 40px;
  margin-right: 20px;
  color: #409EFF;
}
.card-title {
  color: #909399;
  font-size: 14px;
}
.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.quick-actions {
  margin: 30px 0;
}
.action-button {
  width: 100%;
  height: 80px;
  font-size: 16px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.action-button i {
  font-size: 24px;
  margin-bottom: 8px;
}

.announcement {
  margin-top: 30px;
}
.announcement-header {
  font-weight: bold;
  color: #303133;
}
.announcement-header i {
  margin-right: 10px;
}
.announcement-content {
  color: #606266;
  line-height: 1.6;
}
</style>